package com.biboheart.adapter.express.support;

import com.biboheart.adapter.express.actuator.GenericActuator;
import com.biboheart.adapter.support.utils.ObjectTypeUtils;
import com.biboheart.adapter.support.utils.TimeUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final class TimeActuator implements GenericActuator {
    @Override
    public Object execute(Object source, Object... args) {
        Object arg1 = args.length > 0 ? args[0] : null;
        String format = null;
        long milli = 0;
        String timeStr = null;
        int type = 1; // 1: 时间戳转时间, 2: 时间转时间戳
        Integer days = null;
        if (arg1 instanceof Integer) {
            days = ObjectTypeUtils.convertType(arg1, Integer.class);
            type = 2;
        } else {
            format = ObjectTypeUtils.convertType(arg1, String.class);
        }
        if (null == source && null == format) {
            type = 2;
        } else if (source instanceof String) {
            Pattern compile = Pattern.compile("[0-9]+");
            String str = ObjectTypeUtils.convertType(source, String.class);
            Matcher matcher = compile.matcher(str);
            if (matcher.find()) {
                type = 2;
                timeStr = str;
            } else {
                format = str;
            }
        } else if (source instanceof Number) {
            milli = ObjectTypeUtils.convertType(source, Long.class);
        }
        if (type == 1) {
            if (milli == 0) {
                milli = System.currentTimeMillis();
            }
            return TimeUtils.formatDateMillis(milli, format);
        } else if (null == timeStr) {
            milli = System.currentTimeMillis();
        } else {
            milli = TimeUtils.getDateMillis(timeStr, format);
        }
        if (days != null) {
            milli = TimeUtils.getDaysMillis(milli, days);
        }
        return milli;
    }
}
